package com.study.common.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class HashUtil {

    public static void main(String[] args) {
        String originalData = "Hello, World!";
        String tamperedData = "Hello, World!"; // 试着修改这个字符串来模拟数据篡改

        String originalHash = generateHash(originalData);
        String tamperedHash = generateHash(tamperedData);

        System.out.println("Original Data: " + originalData);
        System.out.println("Original Hash: " + originalHash);
        System.out.println("Tampered Data: " + tamperedData);
        System.out.println("Tampered Hash: " + tamperedHash);

        if (originalHash.equals(tamperedHash)) {
            System.out.println("正常");
        } else {
            System.out.println("篡改了");
        }
    }

    public static String generateHash(String data) {
        try {
            // 创建MessageDigest实例，指定使用SHA-256算法
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            
            // 计算哈希值
            byte[] hashBytes = digest.digest(data.getBytes());
            
            // 将字节数组转换为十六进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : hashBytes) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1){
                    hexString.append('0');
                }else {
                    hexString.append(hex);
                }
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
}